<template>
    <div class="logo">{{ isOpen ? 'B' : 'BMS' }}</div>
    <n-menu
        ref="menuInstRef"
        v-model:value="route.path"
        inverted
        accordion
        :collapsed-width="64"
        :collapsed-icon-size="22"
        :options="menuOptions"
        :on-update:value="onUpdate"
    />
</template>

<script setup>
import { menu, tileMenu } from '@/router/modules/menu';
import { toRefs, watch } from 'vue';
import { useStore } from '@/store';
import { RouterLink, useRoute } from 'vue-router';
import useIcon from '@/hooks/useIcon';
import { h, ref } from 'vue';

const store = useStore();
const route = useRoute();
const { isOpen } = toRefs(store);
const { renderIcon } = useIcon();
const menuInstRef = ref(null);

function renderLabel(item) {
    return () =>
        h(
            RouterLink,
            {
                to: {
                    path: item.path
                }
            },
            { default: () => item?.meta?.title }
        );
}
const menuOptions = ref([]);
const onUpdate = val => {
    const list = store.pageTabs;
    const target = tileMenu.find(item => item.path === val);
    const obj = {
        path: val,
        title: target.meta.title
    };
    const i = list.findIndex(x => x.path === val);
    if (i === -1) {
        list.push(obj);
        store.setPageTabs(list);
    }
};
const loop = (arr, result = []) => {
    arr.forEach(item => {
        const obj = {
            label: renderLabel(item),
            key: item.path,
            icon: renderIcon(item.meta?.icon)
        };
        if (item.children?.length) {
            obj.label = item.meta?.title;
            obj.children = loop(item.children);
        }
        result.push(obj);
    });
    return result;
};
const init = () => {
    menuOptions.value = loop(menu);
    // onUpdate(route.path)
};
init();
watch(
    () => route.path,
    val => {
        menuInstRef.value?.showOption(val);
    }
);
</script>

<style lang="less" scoped>
.logo {
    height: 80px;
    text-align: center;
    line-height: 80px;
    color: #fff;
    font-size: 30px;
    font-weight: bold;
    background: rgb(0, 20, 40);
}

.el-menu-vertical-demo {
    height: calc(100% - 80px);
    border-right: none;
}
</style>
